package com.yuerenjf.yuerenjinfu.ads;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yuerenjf.yuerenjinfu.MyApplication;
import com.yuerenjf.yuerenjinfu.R;
import com.yuerenjf.yuerenjinfu.activity.MainActivity;
import com.yuerenjf.yuerenjinfu.activity.WebActivity;

import org.xutils.common.util.LogUtil;

import java.io.File;
import java.util.List;

public class StartLoadingActivity extends Activity {

	private final int MSG_LOGIN_SUCCESS = 100;
	private final int MSG_LOGIN_FAIL = 101;
	private final int MSG_VERSION_CHECK_TIMEOUT = 102;
	private final int UPDATE_TEAY_TIME = 103;

	private int delayTime = 5;// 广告4秒倒计时
	private List<Ad> alist;
	private ImageView welComeImg, adImg;
	private RelativeLayout rl;
	private TextView dTime;
	private TextView skipBtn;
	// 是否首次登陆
	private Boolean myIsfirst = null;
	Editor edited = null;
	SharedPreferences share = null;
	private Context context;
	private boolean adIsFinish = false;
	private Ad mAdver = null;
	private LinearLayout mSkipLayout;

	boolean isGoToWeb;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_load_ads);
		MyApplication app= (MyApplication) getApplication();
		context=app.CONTEXT;
		welComeImg = (ImageView) findViewById(R.id.iv_welcome_img);
		rl = (RelativeLayout) findViewById(R.id.rl_show_ad);
		skipBtn = (TextView) findViewById(R.id.ll_ad_skip_btn);

		adImg = (ImageView) findViewById(R.id.iv_ad_img);
		dTime = (TextView) findViewById(R.id.tv_time);
		mSkipLayout= (LinearLayout) findViewById(R.id.load_ads_skip_layout);
		alist = AdvertisementDao.getAdDataList();// 查询广告信息
		LogUtil.i(alist.size()+"---");
		if (alist != null && alist.size() > 0) {
			mAdver = alist.get(alist.size() - 1);
			File f = new File(mAdver.getAndroidimg());// 获取最新的一条广告信息
			if (f.exists() && !isDeadline(alist.get(alist.size() - 1))) {//// 判断文件存在，并且没有过期
				Bitmap b = AdvertiseUtil.scaleImgSize(f);
				adImg.setImageBitmap(b);
				adIsFinish = true;
				b = null;
			}
		}

		mSkipLayout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				jumpToMain();
				finish();
			}
		});
		adImg.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				isGoToWeb=true;
				if ("0".equals(mAdver.getFlag())) {// 0 代表这个广告可以点击
					WebActivity.launchActivity(StartLoadingActivity.this,mAdver.getUrl());
				}
			}
		});

		// 启动一个线程，去删除过期的广告信息
		new Thread(new Runnable() {
			@Override
			public void run() {

				for (Ad ad : alist) {

					if (isDeadline(ad)) {
						// 如果当前广告过期，则删除数据库中的记录，和本地的文件
						LogUtil.i("delete");
						AdvertiseUtil.deleteCachedAdverImg(context,ad);
						AdvertisementDao.deleteAd(ad);
					}
				}
			}
		}).start();
	}

	/**
	 * 判断某个广告是否过期 过期 true 未过期 false
	 *
	 * @param adver
	 * @return
	 */
	private boolean isDeadline(Ad adver) {
		long deadLine = Long.parseLong(adver.getEnd() + "000");
		LogUtil.i("deadLine:"+deadLine);
		// 获取当前时间的时间戳
		long currentLine = AdvertiseUtil.getCurrentDateMil();
		if (currentLine > deadLine) {// 过期
			return true;
		}
		return false;
	}

	protected void onResume() {
		super.onResume();
		// 获取广告
		AdvertiseUtil.getLoadingAd(context);
		/**
		 * 超时设置
		 */
		handler.sendEmptyMessageDelayed(MSG_VERSION_CHECK_TIMEOUT, 1 * 1000);

		if(isGoToWeb){
			handler.sendEmptyMessageDelayed(MSG_LOGIN_SUCCESS,0);
		}

	}

	@Override
	protected void onDestroy() {
		if (handler != null) {
			handler.removeCallbacksAndMessages(null);
			handler.removeMessages(MSG_VERSION_CHECK_TIMEOUT);
			handler = null;
		}
		super.onDestroy();
	}

	private void jumpToMain() {
		startActivity(new Intent(StartLoadingActivity.this, MainActivity.class));
	}

	private Handler handler = new Handler() {

		public void handleMessage(Message msg) {
			switch (msg.what) {
				case MSG_LOGIN_SUCCESS:
					Intent intent = new Intent(StartLoadingActivity.this, MainActivity.class);
					startActivity(intent);
					finish();
					break;
				case MSG_LOGIN_FAIL:

					break;
				case MSG_VERSION_CHECK_TIMEOUT:
					// 启动页面版本检查接口调用：3秒中没有返回，跳转页面
					skipToLoginOrMain();
					break;
				case UPDATE_TEAY_TIME:
					if (adIsFinish) {
						if (delayTime > 0) {
							if(!isGoToWeb){
								welComeImg.setVisibility(View.GONE);
								rl.setVisibility(View.VISIBLE);
								dTime.setText(delayTime + "S");
								handler.sendEmptyMessageDelayed(UPDATE_TEAY_TIME, 1000);
								delayTime--;
							}


						} else {
							jumpToMain();
							finish();
						}
					} else {
						jumpToMain();
						finish();
					}
					break;
			}
		};
	};

	private void skipToLoginOrMain() {
		handler.sendEmptyMessageDelayed(UPDATE_TEAY_TIME, 1000);
	}
}
